import base64
from cryptography.fernet import Fernet
from django.conf import settings

# 确保settings中有SECRET_KEY
def get_crypto_key():
    return base64.urlsafe_b64encode(settings.SECRET_KEY.encode()[:32].ljust(32, b'='))

def encrypt_data(data):
    if not data:
        return data
    f = Fernet(get_crypto_key())
    return f.encrypt(data.encode()).decode()

def decrypt_data(encrypted_data):
    if not encrypted_data:
        return encrypted_data
    f = Fernet(get_crypto_key())
    return f.decrypt(encrypted_data.encode()).decode()